package tacos.data;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.PreparedStatementCreatorFactory;
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;

import org.springframework.stereotype.Repository;
import tacos.Ingredient;
import tacos.Taco;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Repository
/**
 * 使用了SimpleJdbcInsert来进行插入数据
 */
public class JdbcTacoRepository implements TacoRepository {

  private SimpleJdbcInsert tacoInserter;
  private SimpleJdbcInsert tacoIngredientsInserter;

  @Autowired
  public JdbcTacoRepository(JdbcTemplate jdbc) {
    this.tacoInserter = new SimpleJdbcInsert(jdbc)
            .withTableName("Taco")
            .usingGeneratedKeyColumns("id");
    this.tacoIngredientsInserter = new SimpleJdbcInsert(jdbc)
            .withTableName("Taco_Ingredients");
  }

  @Override
  public Taco save(Taco taco) {
    long tacoId = saveTacoInfo(taco);
    taco.setId(tacoId);
    for (Ingredient ingredient : taco.getIngredients()) {
      saveIngredientToTaco(ingredient, tacoId);
    }
    return taco;
  }

  private void saveIngredientToTaco(Ingredient ingredient, long tacoId) {
    Map<String, Object> values = new HashMap<>();
    values.put("taco", tacoId);
    values.put("ingredient", ingredient.getId());
    tacoIngredientsInserter.execute(values);
  }

  private long saveTacoInfo(Taco taco) {
    taco.setCreatedAt(new Date());
    Map<String, Object> values = new HashMap<>();
    values.put("createdAt", taco.getCreatedAt());
    values.put("name", taco.getName());
    long tacoId = tacoInserter
            .executeAndReturnKey(values)
            .longValue();
    return tacoId;
  }
}
